package edu.spec.wechat.kit;

import edu.spec.pms.model.student.Student;
import edu.spec.pms.service.iface.IStudentService;
import edu.spec.pms.service.impl.StudentService;
import edu.spec.wechat.model.TemplateMsg;
import edu.spec.wechat.model.WechatFianlValue;
import edu.spec.wechat.quartz.RefreshAccessTokenTask;
import edu.spec.wechat.web.BeanFactoryContext;
import edu.spec.wechat.web.WechatContext;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.madgecko.basic.kit.BasicKit;
import org.madgecko.basic.util.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * Created by Administrator on 2016/10/21.
 */
public class MessageKit {
//
//    private static Map<String, String> replyMsgs = new HashMap<String, String>();
//    static {
//        replyMsgs.put("123", "你输入了123");
//        replyMsgs.put("hello", "你输入了Hello");
//        replyMsgs.put("go to heel", "滚蛋");
//    }

    /**
     * 将微信发送过来的信息处理成结果文本（能写入Response里）
     * @param req 微信服务器方便本地服务器的请求
     * @return
     */
    public static String handleReceiveMessage(HttpServletRequest req) throws IOException {
        String replayContent = "";
        String bindingUrl = "http://madfrog.51vip.biz/pms/binding";
        //1.将请求信息转化为xml
        Map<String, Object> map = requestMessage2Map(req);
        //0 判断消息是否重复
        DuplicateMessageKit.checkDuplicate(map);

        //1 判断是否绑定学号
        String openId = (String)map.get("FromUserName");
        IStudentService studentService = (IStudentService)BeanFactoryContext.getService("studentService");
        Student student = studentService.loadbyOpenId(openId);
        if(BasicKit.isEmpty(student)){
            replayContent = "<a href=\"" + bindingUrl + "\">请立即点我完成学号绑定。</a>";
        }else {
            //2 将学生信息临以Map的形式保存起来，key是openId，value是Student对象，可以避免后面重复去数据库
            WechatContext.getInstance().addWechatUser(openId, student);
            //2.判断消息的类型
            String messageType = (String)map.get("MsgType");
            //3.事件消息的处理
            if(!BasicKit.isEmpty(messageType) && messageType.trim().equals("event")){
                replayContent = EventMessageKit.handleMessage(map);
            }else {
                replayContent = CommonMessageKit.handleMessage(map);
            }
            replayContent = "你好";
            //4.其他消息的处理（text,image,等7类）
        }
        return MessageCreateKit.createTextMessage(map, replayContent);
    }

    /**
     * 将请求（xml文本）转换为Map
     * @param req
     * @return
     * @throws IOException
     */
    private static Map<String, Object> requestMessage2Map(HttpServletRequest req) throws IOException {
        String xml = request2xmlString(req);
        try {
            Document document = DocumentHelper.parseText(xml);
            Element root = document.getRootElement();
            List<Element> elementList = root.elements();
            Map<String ,Object> map = new HashMap<String, Object>();
            for(Element e : elementList){
                map.put(e.getName(), e.getTextTrim());
            }
            return map;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String request2xmlString(HttpServletRequest req) throws IOException {
        BufferedReader br = null;
        String str = null;
        br = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuffer sb = new StringBuffer();
        while ((str=br.readLine())!=null){
            sb.append(str);
        }
        return sb.toString();
    }

    public static String map2xmlString(Map<String, String> map){
        try {
            Document d = DocumentHelper.createDocument();
            Element root = d.addElement("xml");
            Set<String> keys = map.keySet();
            for(String k : keys){
                String val = map.get(k);
                if (val.indexOf("<a")>=0){
                    root.addElement(k).addCDATA(val);
                }else {
                    root.addElement(k).addText(val);
                }
            }
            StringWriter sw = new StringWriter();
            d.write(sw);
            return sw.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static String handleMsg(Map<String, String> msgMap) throws IOException {
//        String msgType = msgMap.get("MsgType");
//        if(msgType.equals(WechatFianlValue.MSG_EVENT_TYPE)){
//
//        }else if(msgType.equals(WechatFianlValue.MSG_TEXT_TYPE)){
//            return textTypeHandler(msgMap);
//        }
//        return "";
//    }
//
//    private static String textTypeHandler(Map<String, String> msgMap) throws IOException {
//        String con = msgMap.get("Content");
//        String replyCon = "你请求的消息不存在";
//        if(replyMsgs.containsKey(con)){
//            replyCon = replyMsgs.get(con);
//        }
//        HashMap<String, String> map = new HashMap<String, String>();
//        map.put("ToUserName", msgMap.get("FromUserName"));
//        map.put("FromUserName", msgMap.get("ToUserName"));
//        map.put("CreateTime", new Date().getTime() + "");
//        map.put("MsgType", "text");
//        map.put("Content", replyCon);
//        return map2xmlString(map);
//    }
//
//    public static String postTemplateMsg(TemplateMsg msg){
//        String url = WechatFianlValue.SEND_TEMPLATE_MSG;
//        url = url.replace("ACCESS_TOKEN", RefreshAccessTokenTask.at);
//        String data = JsonUtil.getInstance().obj2json(msg);
//        return WechatKit.postReq(url, data, "application/json");
//    }
}
